<template>
  <el-dialog v-model="visible" title="请选择角色" width="850" :before-close="handleClose">
    <div class="role-list">
      <el-card shadow="never" v-for="(item, index) in list" :key="item.schoolId">
        <div class="shop">
          <div class="shop-index">{{ getIndex(index + 1)  }}</div>
          <div class="shop-info">
            <div class="name">{{ item.schoolName }}</div>
            <div class="role">所属角色：{{ item.roleNames }}</div>
          </div>
        </div>
        <span v-if="schoolId == item.schoolId">当前角色</span>
        <el-button type="primary" @click="handleLogin(item.schoolId, item.roleNames)" v-else>登录</el-button>
      </el-card>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, computed } from "vue";
import { GlobalStore } from "@/stores";
import { useRouter } from "vue-router";
import { ElNotification } from "element-plus";
import { HOME_URL } from "@/config/config";
import { getTimeState } from "@/utils/util";
import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
import { loginSchool } from '@/api/modules/login'

const visible = ref(false)
const list = ref([])
const router = useRouter();
const globalStore = GlobalStore();
const getIndex = computed(() => (index) => {
  return index >= 10 ? index : '0' + index
})
const schoolId = computed(() => globalStore.userInfo.schoolId)

async function handleLogin(schoolId, roleNames) {
  const userInfo = globalStore.userInfo
  const { data } = await loginSchool({ schoolId })
  userInfo.roleNames = roleNames
  Object.assign(userInfo, data.userInfo)
  // 添加动态路由
  await initDynamicRouter();
  // 跳转到首页
  router.push(HOME_URL);
  ElNotification({
    title: getTimeState(),
    message: "欢迎登录海青课后服务管理系统",
    type: "success",
    duration: 3000
  });
  handleClose()
}
/** 接收父组件传过来的参数 */
function acceptParams (schoolList) {
  visible.value = true
  schoolList.forEach(item => {
    item.roleNames = item.roleList.map(item => item.roleName).join('、')
  });
  list.value = schoolList
};
function handleClose () {
  visible.value = false
}
defineExpose({
  acceptParams
})
</script>
<style lang="scss" scoped>
  .role-list {
    .el-card {
      ::v-deep .el-card__body {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      &:not(:last-of-type) {
        margin-bottom: 20px;
      }
    }
    .shop {
      display: flex;
      align-items: center;
      .shop-index {
        font-size: 18px;
        font-weight: bold;
        color: #2c3146;
        margin-right: 20px;
      }
      .shop-info {
        .name {
          font-size: 16px;
          text-align: left;
        }
        .role {
          font-size: 14px;
          margin-top: 6px;
          color: #777B86;
        }
      }
    }
  }
</style>
